import {createSlice, createAsyncThunk} from '@reduxjs/toolkit'
import { getSentence } from '../../api'

const countSlice = createSlice({
    name:'count',
    initialState:{
        num:0
    },
    reducers:{
        addNum(state, {payload}){
            state.num += payload
        }
    },
    extraReducers:builder=>{
        builder
            .addCase(asyncAddNum.fulfilled, (state, {payload})=>{
                console.log('payload: ', payload);
                state.num += payload
            })
    }
})

/**
 * 切片：
 * 1. 默认暴露 reducer
 * 2. 分别暴露 同步的 actionCreator
 * 3. 分别暴露 异步的 actionCreator
 */
export default countSlice.reducer
export const {addNum} = countSlice.actions

export const asyncAddNum = createAsyncThunk('count/addNum', async payload=>{
    // 异步的操作
    let res = await getSentence()

    return res.length;
})
